<?php
namespace app\admin\controller\system;
use app\common\annotation\NodeAnnotation;
use app\common\controller\Admin;
use app\common\lib\Img;
use app\common\traits\ControllerCurd;
use think\Request;
/**
 * @package app\admin\controller\system
 * @NodeAnnotation(
 *     title="资源管理",
 *     is_menu=0,
 *     is_view=0
 * )
 */
class Asset extends Admin
{
    use ControllerCurd;
    public $model;

    public function initialize()
    {
        parent::initialize();
        $this->model= new \app\admin\model\system\Asset();
    }

    /**
     * @NodeAnnotation(
     *     title="资源列表",
     *     parent="admin/system.asset",
     *     MenuRoot="admin/system.setting"
     * )
     */
    public function index(Request $request)
    {

        $data = $this->model->field('a.*,u.username,u.email user_email,u.nickname user_nickname')
            ->alias('a')
            ->join('cp_admin u', 'a.user_id = u.id')
            ->order('create_time', 'DESC')
            ->paginate(10);
        $this->assign([
            "dataList"     => $data,
        ]);
        return $this->fetch();
    }


    /**
     * @NodeAnnotation(
     *     title="删除资源",
     *     parent="admin/system.asset",
     *     MenuRoot="admin/system.setting",
     *     is_view=0,
     *     is_menu=0
     * )
     */
    public function delasset(Request $request)
    {
        $this->del('',function($model,$input,$data){
            foreach ($data as $k=>$vo){
                if(file_exists(dirname(app_path()).'/public/upload/'.$vo['file_path'])){
                    @unlink(dirname(app_path()).'/public/upload/'.$vo['file_path']);
                }
            }
        });
    }

    /**
     * @NodeAnnotation(
     *     title="压缩图像",
     *     parent="admin/system.asset",
     *     MenuRoot="admin/system.setting",
     *     is_view=0,
     *     is_menu=0
     * )
     */
    public function compressImg($img_id)
    {
        $data = $this->model->where("id",$img_id)->find();
        $file_path =  dirname(app_path()).'/public/upload/'.$data['file_path'];
        if(!file_exists($file_path))
        {
            $this->error("文件不存在，无法进行压缩处理");
        }
        $comporess = new Img($file_path,1);
        $res  = $comporess->compressImg($file_path);

        if($res)
        {
            $this->success("压缩成功");
        }

    }
}